package com.chinaunicom.emergency.config.translator;

import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.emergency.exception.OAuthException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

import java.util.Map;

/**
 * @Description: 资源服务器异常自定义捕获
 * @Author liliang
 * @Date 2020/1/20 10:35
 * @Version 1.0
 */
public class OAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception exception) throws Exception {
        if (exception instanceof OAuth2Exception) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) exception;
            Map<String,String> map = oAuth2Exception.getAdditionalInformation();
            if(null != map && map.containsKey("needCode")){
                //说明需要验证码
                return ResponseEntity
                        .status(oAuth2Exception.getHttpErrorCode())
                        .body(new OAuthException(oAuth2Exception.getMessage(),true));
            }
            return ResponseEntity
                    .status(oAuth2Exception.getHttpErrorCode())
                    .body(new OAuthException(oAuth2Exception.getMessage()));
        }else if(exception instanceof AuthenticationException){
            AuthenticationException authenticationException = (AuthenticationException) exception;
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(new OAuthException(authenticationException.getMessage()));
        }
        return ResponseEntity
                .status(HttpStatus.OK)
                .body(new OAuthException(exception.getMessage()));
    }
}
